package com.fang.controller;

import com.fang.pojo.JsonResult;
import com.fang.pojo.Provice;
import com.fang.service.ProviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@SuppressWarnings("all")
@RestController
@RequestMapping("/provice")
@CrossOrigin
@Slf4j  // 日志对象
public class ProviceController {

    @Autowired
    private ProviceService proviceService;

    /**
     * 修改省份信息
     * */
    @PostMapping("/update")
    public JsonResult update(@RequestBody Provice provice) {
        JsonResult jsonResult = new JsonResult();
        try {
            proviceService.update(provice);
            jsonResult.setState(true).setMsg("修改省份信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(false).setMsg("修改省份信息失败");
        }
        return jsonResult;
    }

    /**
     * 查询一条省份的信息
     * */
    @GetMapping("/findOne")
    public Provice findOne(Integer id) {
        return proviceService.findOne(id);
    }

    /**
     * 删除省份
     * */
    @GetMapping("/delete")
    public JsonResult delete(Integer id) {
        JsonResult jsonResult = new JsonResult();
        try {
            proviceService.delete(id);
            jsonResult.setState(true).setMsg("删除省份成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(false).setMsg("删除省份失败");
        }
        return jsonResult;
    }

    /**
     * 添加省份信息
     * */
    @PostMapping("/save")
    public JsonResult save(@RequestBody Provice provice) {
        JsonResult jsonResult = new JsonResult();
        try {
            proviceService.save(provice);
            jsonResult.setState(true).setMsg("添加省份信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(false).setMsg("添加省份信息失败");
        }
        return jsonResult;
    }

    /**
     * 查询所有省份
     * */
    @GetMapping("/findByPage")
    public Map<String, Object> findByPage(Integer page, Integer rows) {
        page = page == null ? 1 : page;
        rows = rows == null ? 4 : rows;
        Map<String, Object> map = new HashMap<>();
        // 分页查询
        List<Provice> provices = proviceService.findByPage(page, rows);
        // 计算总页数
        Integer totals = proviceService.findTotals();
        Integer totalPage = totals % rows == 0 ? totals / rows : (totals / rows) + 1;
        map.put("provices", provices);
        map.put("totals", totals);
        map.put("totalPage", totalPage);
        map.put("page", page);
        return map;
    }
}
